$(function() {
	var page=1;
	var main;
    var data={};
    data.page=page;
    data.pagenum=10;
    laydate.render({
	  elem: '.time'
	  ,range: true,
	  done:function(value, date, endDate){
	  	arr = value.split(' - ')
	  	$("input[name='order_start']").val(arr[0])
	  	$("input[name='order_end']").val(arr[1])
	  }
	});
    $('#more').on('click',function(){
    	if($('#showmore').css('display')=='none'){
    		$('#showmore').css('display','block')
    	}else{
    		$('#showmore').css('display','none')
    	}
    });
    var where_json={};
    {if $Think.get.order_no}
		where_json.order_no=['like','%{$Think.get.order_no}%']
	{/if}
	{if $Think.get.company_name}
		where_json.company_name=['like','%{$Think.get.company_name}%']
	{/if}
	{if $Think.get.name}
		if($('.orderertype').val()==1){
			where_json.passenger_name=['like','%{$Think.get.name}%']
		}else{
			where_json.orderer=['like','%{$Think.get.name}%']
		}
	{/if}
	{if $Think.get.phone}
		where_json.passenger_phone=['like','%{$Think.get.phone}%']
	{/if}
	{if $Think.get.state}
		where_json.order_state=['in','{$Think.get.state}']
	{/if}
	{if $Think.get.order_start}
		where_json.apply_time=['between time',['{$Think.get.order_start}','{$Think.get.order_end}']]
	{/if}
	
	data.where_json=JSON.stringify(where_json)
    ajaxorder(data)
	{if $Think.get.state==1||$Think.get.state==3||$Think.get.state==2}
		main=[[ //表头
		{field: 'order_no', width:200, title: '订单号',  sort: true, fixed: 'left'}
        ,{field: 'apply_time',width:200, title: '申请时间',  sort: true}
        ,{field: 'approval_time',width:200, title: '批准时间'} 
        ,{field: 'orders_time',width:200, title: '接单时间'}
        ,{field: 'order_type2', width:100, title: '订单类型', sort: true}
        ,{field:'orderer', width:150,title:'申请人'}
        ,{field:'approval',width:150, title:'审核人'}
        ,{field:'from_addr', width:300, title:'出发地'}
        ,{field:'to_addr', width:300, title:'目的地'}
        ,{field:'use_type2',width:100, title:'用车类型'}
        ,{field:'use_explain',width:200, title:'用车说明'}
        ,{field:'order_state2', title:'订单状态'}
        {if $Think.get.state==2}
        ,{ title: '操作', width:150, toolbar:'#operation_1',fixed: 'right'}
        {else/}
        ,{ title: '操作',width:100, toolbar:'#operation_all',fixed: 'right'}
        {/if}
    ]];
	{elseif $Think.get.state==0||$Think.get.state==4||!$Think.get.state/}
	main=[[ //表头
		{field: 'order_no', width:200, title: '订单号',  sort: true, fixed: 'left'}
        ,{field: 'apply_time', width:200, title: '申请时间',  sort: true}
        ,{field: 'approval_time', width:200, title: '批准时间'} 
        ,{field: 'orders_time', width:200, title: '接单时间'}
        ,{field: 'car_type_name', width:200, title: '车辆类型', sort: true}
        ,{field:'order_type2', width:120, title:'订单类别'}
        ,{field:'passenger_name', title:'乘客'}
        ,{field:'driver_name', title:'司机'}
        ,{field:'from_addr', width:300, title:'出发地'}
        ,{field:'to_addr', width:300, title:'目的地'}
        ,{field:'order_state2', title:'状态'}
        ,{ title: '操作',width:100, toolbar:'#operation_all',fixed: 'right'}
    ]];
	{elseif $Think.get.state==5||$Think.get.state==6/}
	main=[[ //表头
		 {field: 'order_no', width:200, title: '订单号',  sort: true, fixed: 'left'}
        ,{field: 'appointment_time',width:200, title: '计划出发时间',  sort: true}
        ,{field: 'arrive_time',width:200, title: '到达出发地时间'} 
        ,{field: 'ride_time',width:200, title: '实际出发时间'}
        ,{field: 'order_type2', title: '订单类型', sort: true}
        ,{field:'passenger_name', title:'乘客'}
        ,{field:'driver_name', title:'司机'}
        ,{field:'from_addr', title:'出发地'}
        ,{field:'to_addr', title:'目的地'}
       ,{ title: '操作',width:150, toolbar:'#operation_2',fixed: 'right'}
    ]];
    
	{else/}
	main=[[ //表头
		{field: 'order_no', title: '订单号', width:200,  sort: true, fixed: 'left'}
        ,{field: 'ride_time',width:200, title: '计划出发时间',  sort: true}
        ,{field: 'arrive_time',width:200, title: '到达出发地时间'} 
        ,{field: 'ride_time',width:200, title: '实际出发时间'}
        ,{field: 'arrive_time',width:200, title: '实际到达时间', sort: true}
        ,{field:'order_type2', title:'订单类型'}
        ,{field:'passenger_name', title:'乘客'}
        ,{field:'driver_name', title:'司机'}
        ,{field:'meter', title:'里程'}
         ,{field:'use_time', title:'耗时'}
        ,{field:'passenger_money', title:'费用'}
       
        ,{field:'order_state2', title:'状态'}
        ,{ title: '操作', toolbar:'#operation_all',fixed: 'right'}
    ]];
	{/if}
	function ajaxorder(data){
		Load()
		$.ajax({
			type:"post",
			url:"{:url('/adminapi/Order/orderList')}",
			data:data,
			success:function(res){
				Load(1)
				if(res.code==1){
					console.log(res)
					  var table = layui.table
					  ,form = layui.form;
					  res=orderstate(res)
					  //展示已知数据
						table.render({
						  	elem: '#order'
						    ,cellMinWidth: 80
						    ,cols: main
							,data: res.data
							,even: true
						});
						$('.pagination').html(pagechang1(res.count, 10, page))
						table.on('tool(order)', function(obj){
							  var data = obj.data; //获得当前行数据
							  var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
							  var tr = obj.tr; //获得当前行 tr 的DOM对象
							 
							  if(layEvent === 'showmap'){ //查看
							  	layer.open({
									type: 1,
									area: ['60%', '60%'],
									title: false,
									id: 'layerDemo' ,
									content: '<div id="showlocation" style="width:99%;height:99%;margin:1%"></div>',
									btn: ['确认'],
									
									btn2: function() {
										layer.closeAll();
									},
									btnAlign: 'c',
									shade: 0 ,
									yes: function() {
										layer.closeAll();
									},
									success: function(layero) {
										console.log(11)
										var trackload = layer.load(1, {
											shade: [0.1, '#fff'] //0.1透明度的白色背景
										});
										var map = new AMap.Map('showlocation', {
											resizeEnable: true,
											zoom: 8,
											center: [118.57, 24.82]
										});
										AMapUI.load(['ui/misc/PathSimplifier'], function(PathSimplifier) {
											var pathSimplifierIns = new PathSimplifier({
												zIndex: 100,
												map: map, //所属的地图实例
												getPath: function(pathData, pathIndex) {
													//返回轨迹数据中的节点坐标信息，[AMap.LngLat, AMap.LngLat...] 或者 [[lng|number,lat|number],...]
													return pathData.path;
												},
												getHoverTitle: function(pathData, pathIndex, pointIndex) {
													//返回鼠标悬停时显示的信息
													if(pointIndex >= 0) {
														//鼠标悬停在某个轨迹节点上
														return pathData.name + '，点:' + pointIndex + '/' + pathData.path.length;
													}
													//鼠标悬停在节点之间的连线上
													return pathData.name + '，点数量' + pathData.path.length;
												},
												renderOptions: {
													//轨迹线的样式
													pathLineStyle: {
														strokeStyle: 'red',
														lineWidth: 6,
														dirArrowStyle: true
													}
												}
											});
											$.ajax({
												type: "post",
												url: "{:url('/admin/order/getTrack')}",
												data: {
													oid: data.order_id
												},
												success: function(res) {
													layer.close(trackload);
													var allpath = []
													var speed=0;
													if(typeof res == 'string') {
														var opath1 = JSON.parse(res).data;
													} else {
														var opath1 = res.data;
													}
													var opath2=[];
													var opath=[];
													//根据时间进行排序
													if(opath1.length>1){
														for(var rankidx=0;rankidx<opath1.length;rankidx++){
															opath2.push(opath1[rankidx].time)
														}
														opath2.sort()
														for(var k=0;k<opath2.length;k++){
															for(var j=0;j<opath1.length;j++){
																if(opath2[k]==opath1[j].time){
																	opath.push(opath1[j])
																}
															}
														}
													console.log(opath)
													
													for(var oi = 0; oi < opath.length; oi++) {
														var oarr = []
														oarr.push(opath[oi].longitude)
														oarr.push(opath[oi].latitude)
														allpath.push(oarr)
													}
													initPage(PathSimplifier, pathSimplifierIns, map, allpath)
													}else{
														Err('暂无轨迹信息')
													}
												},
												error:function(){
													layer.close(trackload);
													Err('请求失败')
												}
											});
										})
									}
								});
								
							  } else if(layEvent === 'changedriver'){ //删除
							   layer.open({
								    type: 1,
								    title:'订单改派',
								    skin: 'layui-layer-rim', //加上边框
								    area: ['300px', '240px'], //宽高
								    content: `<div class="am-u-sm-12">
								    		<form class="am-form tpl-form-border-form" data-check="1" data-ajax="1">
								    		<div class='am-u-sm-12' style='margin-bottom:10px;font-size:12px'>
								    			订单号:${data.order_no}
								    		</div>
								    		<div class='am-u-sm-12' style='margin-bottom:10px'>
								  				<input type="hidden" class="driver_id" name="driver_id"/>
												<input type="text" class="am-form-field tpl-form-no-bg driver" style="line-height: 21px;" data-department="1"  placeholder="请选择司机" readonly="" >
								  			</div>
								  			<div class='am-u-sm-12' style='margin-bottom:10px'>
								  				<input type="hidden" class="CarId" name="car_id" value="" />
												<input type="text" class="am-form-field tpl-form-no-bg  car_number" value="" placeholder="请选择车辆"  readonly=""/>
								  			</div>
								  			<div class='am-u-sm-12'>
								  				<button type='button' class='am-btn am-btn-sm am-btn-primary am-radius change_sub'>提交</button>
								  			</div>
								  			</form>
								  			</div>`,
								  	success:function(){
								  		$('.driver').on('click',function(){
											choosecar("{:url('admin/driver/index',['op'=>'search'])}")
										});
										$('.car_number').on('click',function(){
											choosecar("{:url('/admin/car/index',['op'=>'search'])}")
										});
										$('.change_sub').on('click',function(){
											var driver_id=$('.driver_id').val()
											
											if($('.driver_id').val()){
												if($('.CarId').val()){
													Load()
													$.ajax({
														type:"post",
														url:"{:url('redispatch')}",
														data:{
															car_number:$('.car_number').val(),
															driver_id:$('.driver_id').val(),
															car_id:$('.CarId').val(),
															order_id:order_id
														},
														success:function(res){
															Load(1)
															console.log(res)
						//									window.location.reload()
															if(res.code==1){
																Msg('改派成功')
																window.history.go(0)
															}else{
																Err(res.msg)
															}
														},
														error:function(res){
															Load(1)
															Err('请求失败')
														}
													});
												}else{
													Err('请选择车辆')
												}
											}else{
												Err('请选择司机')
											}
											
										});
								  	}
								});
							  } else if(layEvent === 'dispatch'){ //编辑
							  window.location.href= "{:url('/admin/order/dispatch')}?order_id="+data.order_id
							  } 
						});
				}else{
					Err(res.msg)
				}
			},
			error:function(){
				Load(1)
				Err('请求失败')
			}
		})
	}
	function initPage(PathSimplifier, pathSimplifierIns, map, path) {
		var alljourney=0
		for(var pidx=0;pidx<path.length-1;pidx++){
			var  journey=Math.sqrt(Math.pow((path[pidx][0]-path[pidx+1][0]),2)+Math.pow((path[pidx][1]-path[pidx+1][1]),2))*111000
			alljourney+=journey
		}
		
		console.log(alljourney)
		//这里构建两条简单的轨迹，仅作示例
		pathSimplifierIns.setData([{
			name: '轨迹',
			path: path
		}]);
		
		//创建一个巡航器
		var navg0 = pathSimplifierIns.createPathNavigator(0, //关联第1条轨迹
			{
				loop: true, //循环播放
				speed:alljourney/10,
				pathNavigatorStyle: {
					width: 16,
					height: 32,
					content: PathSimplifier.Render.Canvas.getImageContent('{$static_dir}/assets/img/car-gray.png', onload, onerror),
					strokeStyle: null,
					fillStyle: null
				}
			});

		navg0.start();
	}
	
	
	
	
	
})